<template>
  <el-dialog
    v-model="is_show"
    :close-on-click-modal="false"
    append-to-body
    title="编辑任务"
    width="650"
    class="dialogForm"
    :before-close="beforeClose"
  >
    <el-form
      :model="formParams"
      :rules="rulesForm"
      label-width="110px"
      ref="ruleFormRef"
    >
      <el-form-item label="任务标题" prop="title">
        <el-input
          v-model="formParams.title"
          placeholder="请输入任务标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          v-model="formParams.startTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker
          v-model="formParams.endTime"
          type="datetime"
          value-format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="关联项目" prop="businessType">
        <el-select
          v-model="formParams.businessType"
          placeholder="项目类型"
          clearable
          :disabled="isDisabled"
          style="width: 30%; margin-right: 2%"
        >
          <el-option
            v-for="item in rsgl_associated_item"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
        <el-input
          style="width: 68%"
          v-model="formParams.businessName"
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item
        label="问题类型"
        prop="questionType"
        v-if="formParams.businessType == '1'"
      >
        <el-select
          v-model="formParams.questionType"
          placeholder="项目类型"
          clearable
          style="width: 100%"
          :disabled="isDisabled"
        >
          <el-option
            v-for="item in rsgl_question_type"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="负责人员">
        <el-input
          v-model="formParams.director"
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item label="参与人员">
        <el-input
          v-model="formParams.players"
          :disabled="isDisabled"
        ></el-input>
      </el-form-item>
      <el-form-item label="紧要程度">
        <el-radio-group
          v-model="formParams.impSign"
          @change="radioClick($event)"
          :disabled="isDisabled"
        >
          <template v-for="(item, index) in rsgl_urgent_status" :key="index">
            <el-radio-button :label="item.value" :value="item.value">{{
              item.label
            }}</el-radio-button>
          </template>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="任务提醒">
        <el-select
          :disabled="isDisabled"
          v-model="formParams.serviceType"
          placeholder="任务提醒"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="item in task_reminder_time"
            :label="item.label"
            :value="item.value"
            :key="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提醒方式">
        <el-checkbox-group
          v-model="formParams.reminderMethod"
          :disabled="isDisabled"
        >
          <template v-for="(item, index) in reminder_method" :key="index">
            <el-checkbox :label="item.value" :value="item.value">{{
              item.label
            }}</el-checkbox>
          </template>
        </el-checkbox-group>
      </el-form-item> -->
      <el-form-item label="任务描述">
        <el-input
          type="textarea"
          placeholder="请输入内容"
          v-model="formParams.remark"
          maxlength="200"
          :rows="4"
          show-word-limit
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传附件：">
        <el-upload
          v-model:file-list="formParams.fileList"
          class="upload-demo"
          action="#"
          :before-upload="beforeAvatarUpload"
          :http-request="handleFileChange"
          accept=".rar, .zip, .doc, .docx, .pdf"
          :show-file-list="false"
          style="margin-right: 6px"
        >
          <el-button type="default" style="font-size: 14px"
            ><el-icon><UploadFilled /></el-icon>上传文件</el-button
          >
          <template #tip>
            <div class="el-upload__tip float-right">
              支持格式：.rar .zip .doc .docx .pdf ，单个文件不能超过20MB
            </div>
          </template>
        </el-upload>
        <div class="text-14px mt-10px" style="width: 100%">
          <div v-for="(item, index) in fileList" :key="item.fileId">
            <a :href="item.url" target="_blank" class="text-#409eff">{{
              item.origFileName
            }}</a>
            <el-button text plain @click="delFileName(index)">删除</el-button>
          </div>
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="beforeClose">取 消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="btnLoading">
          确 认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup name="addTaskManage">
import { addTaskList, getTaskDetail, updateTadk } from '@/api/taskManage/task'
import { ref, reactive, computed, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import useCommonStore from '@/store/modules/common'
import { uploadFile, delFile } from '@/api/salesManage/contractManage'
const { proxy } = getCurrentInstance()
const is_show = computed(() => {
  return true
})
/*** 文件上传 start */
let fileList = ref([])
// 通用数据store
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const {
  task_reminder_time,
  rsgl_urgent_status,
  rsgl_task_status,
  rsgl_associated_item,
  reminder_method,
  rsgl_question_type //问题类型
} = proxy.useDict(
  'task_reminder_time',
  'rsgl_urgent_status',
  'rsgl_task_status',
  'rsgl_associated_item',
  'reminder_method',
  'rsgl_question_type' //问题类型
)
const data = reactive({
  formParams: {
    title: null,
    startTime: null,
    endTime: null,
    impSign: '1',
    directorId: null, //负责人
    playersId: null, //参与人员
    serviceType: null, //任务提醒
    // status: null, //状态
    reminderMethod: [], //提醒方式
    remark: null,
    filePath: [],
    fileName: [] //文件名
  },
  // 表单校验
  rulesForm: {
    title: [{ required: true, message: '任务标题不能为空', trigger: 'blur' }],
    startTime: [
      { required: true, message: '开始时间不能为空', trigger: 'blur' }
    ],
    endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }]
  }
})
const { formParams, rulesForm } = toRefs(data)
const isDisabled = ref(true)
const props = defineProps({
  taskId: {
    type: Object
  }
})

async function init() {
  if (props.taskId) {
    await getTaskDetails()
  }
}
init()
async function getTaskDetails() {
  const response = await getTaskDetail({ id: props.taskId })
  formParams.value = response.data
  formParams.value.reminderMethod = response.data.reminderMethod
    ? response.data.reminderMethod.split(',')
    : []

  let newArr = []
  let filePathList = response.data.filePath
    ? response.data.filePath.split(',')
    : ''
  let fileNameList = response.data.fileName
    ? response.data.fileName.split(',')
    : ''
  if (response.data.filePath) {
    filePathList.map(item => {
      newArr.push({
        url: item,
        fileId: '',
        origFileName: '',
        fileName: item
          .substring(item.lastIndexOf('attach/'))
          .replace('attach/', '')
      })
    })

    console.log('newArr', newArr)
    fileNameList.map((item, i) => {
      if (newArr[i]) {
        newArr[i].origFileName = item
      }
    })
    fileList.value = newArr
  }
  formParams.value.directorId = response.data.directorId
  formParams.value.playersId = response.data.playersId

  console.log('formParams', formParams.value)
  console.log('fileList', fileList.value)
}

const btnLoading = ref(false) //按钮加载状态
//关闭
function beforeClose() {
  proxy.$emit('closeForm')
}

const radioClick = tab => {
  console.log('点击了', tab)
}
//保存
async function handleSubmit() {
  proxy.$refs['ruleFormRef'].validate(valid => {
    if (valid) {
      console.log('formParams===', formParams.value)
      let data = JSON.parse(JSON.stringify(formParams.value))
      data.fileName = []
      data.filePath = []
      delete data.fileList

      for (let i = 0; i < fileList.value.length; i++) {
        data.fileName.push(fileList.value[i].origFileName)
        data.filePath.push(fileList.value[i].url)
      }
      data.fileName = data.fileName ? data.fileName.toString() : ''
      data.filePath = data.filePath ? data.filePath.toString() : ''
      data.reminderMethod = data.reminderMethod
        ? data.reminderMethod.toString()
        : ''
      console.log('data', data)
      btnLoading.value = true
      updateTadk(data).then(res => {
        if (res.code === 200) {
          console.log('res', res)
          btnLoading.value = false
          proxy.$modal.msgSuccess('修改成功!')
          proxy.$emit('closeForm')
        } else {
          btnLoading.value = false
        }

        //   proxy.$emit('refreshList')
      })
    }
  })
}
/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}
// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}
//删除文件
async function delFileName(index) {
  console.log('fileList.value====', fileList.value)
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      console.log('file', file)
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    proxy.$modal.msgError(error)
  }
}
</script>

<style lang="scss">
.dialogForm {
  .el-dialog__header {
    @apply mr-0  text-#666 font-semibold bg-#f5f5f5;
  }
  .footer {
    @apply text-right border-t border-t-solid border-gray-100 pt-20px mt-20px;
  }
}
</style>
